
<template>
  <div class="player" v-show="playlist.length>0">
    <transition name="normal"
    @enter="enter"
    @after-enter="afterEnter"
    @leave="leave"
    @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
      <div class="background">
          <img width="100%" height="100%" :src="picUrl.picUrl">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="icons icons-xiangxia"></i>
          </div>
          <h1 class="title" v-html="song_detail.name"></h1>
          <h2 class="subtitle" v-html="song_detail.singer"></h2>
        </div>
        <div class="middle"
        @touchstart.prevent="middleTouchStart"
        @touchmove.prevent="middleTouchMove"
        @touchend="middleTouchEnd"
        >
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdCls">
                <img class="image" :src="picUrl.picUrl">>
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric"></div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <Scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p ref="lyricLine"
                class="text"
                :class="{'current': currentLineNum == index}"
                v-for="(line,index) in currentLyric.lines" :key="index">{{line.txt}}</p>
              </div>
            </div>
          </Scroll>
        </div>
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active': currentShow == 'cd'}"></span>
            <span class="dot" :class="{'active': currentShow == 'lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
            </div>
            <span class="time time-r">{{format(song_detail.duration/1000)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left" @click="changeMode">
              <i class="icons" :class="iconMode"></i>
            </div>
            <div class="icon i-left"  @click="prev">
              <i  class="icons icons-fast-backward"></i>
            </div>
            <div class="icon i-center"  @click="tooglePlaying">
              <i style="font-size:22px" class="icons" :class="playIcon"></i>
            </div>
            <div class="icon i-right" @click="next">
              <i  class="icons icons-fast-forward"></i>
            </div>
            <div class="icon i-right">
              <i class="icons icons-shoucang" ></i>
            </div>
          </div>
        </div>
    </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" ref="miniPlayer" v-show="!fullScreen" @click="open">
      <div class="icon i-img">
        <img width="60" height="60" :class="cdCls" :src="picUrl.picUrl">
      </div>
      <div class="text">
        <h2 class="name" v-html="song_detail.name"></h2>
        <p class="desc" v-html="song_detail.singer"></p>
      </div>
        <div class="control">
         <div class="icon i-center" @click.stop="tooglePlaying">
            <ProgressCircle :percent="percent">
              <i :class="miniIcon" class="icon-mini" style="z-index:-1;color:#fff;"></i>
            </ProgressCircle>
          </div>
        </div>
      <!-- <div class="control">
        <i class="icon-playlist"></i>
      </div> -->
    </div>
    </transition>
    <audio ref="audio" :src="song_detail.url"  @canplay="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
    <div v-show="playlist.length == 0">
      <Loading />
    </div>
  </div>
</template>

<script>
import {mapGetters, mapMutations} from 'vuex'
import animations from 'create-keyframe-animation'
import {songDetail, getUrl,checkMusic,getLyrics,singerDetail } from 'api/singer'
import ProgressBar from 'base/progress-bar/progress-bar'
import ProgressCircle from 'base/progress-circle/progress-circle'
import {prefixStyle} from 'common/js/dom'
import {playMode} from 'common/js/config'
import {shuffle} from 'common/js/util'
import Lyric from 'lyric-parser'
import Scroll from 'base/scroll/scroll'
import Loading from 'base/loading/loading'
const transform = prefixStyle('transform')
const transitionDuration = prefixStyle('transitionDuration')
export default {
  components:{
    ProgressBar,
    ProgressCircle,
    Scroll,
    Loading
  },
  data () {
    return {
      picUrl: {},
      song_detail: {},
      getplaylist: [],
      someReady: false,
      currentTime: 0,
      currentLyric: {},
      currentLineNum: 0,
      playingLyric: '',
      currentShow: 'cd',
      playingLyric: ''
    }
  },
  created() {
    this.touch = {}
  },
  computed: {
    iconMode() {
      console.log(this.mode)
      /*
        0 单曲循环 1 顺序播放 2 随机播放
      */
      return this.mode === playMode.sequence ? 'icons-xunhuanbofang' : this.mode === playMode.loop ? 'icons-danquxunhuan' : 'icons-suiji'
    },
    cdCls() {
      return this.playing ? 'play' : 'play pause'
    },
    playIcon() {
      return this.playing ? 'icons-bofang' : 'icons-caret-right'
    },
    miniIcon() {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    percent(){
      if(this.song_detail.duration){
        return this.currentTime / (this.song_detail.duration / 1000)
      }
      // else{
      //   console.error('hi man, your song of duration is none')
      // }
    },
    ...mapGetters([
      'fullScreen',
      'currentSong',
      'playing',
      'playlist',
      'currentIndex',
      'mode',
      'sequenceList'
    ])
  },
  watch: {
    /*
      当前播放歌曲相关
      setCurrenIndex 设置不同的歌曲索引 会触发对歌曲的重新计算播放

    */
    currentSong (newSong,oldSong) {
      if(this.currentSong.id) {
        let id = this.currentSong.id
        checkMusic(id)
        .then(res => {
          if(res) {
              songDetail(id).then(res => {
                this.picUrl = res.data.body.songs[0].al
              getUrl(id).then((song) => {
                let data = song.data.body.data[0]
                Object.assign(this.currentSong,data)
                this.song_detail = this.currentSong
                console.log('getUrl')
                console.log(this.song_detail)
                if(!this.song_detail.duration) {
                    /*
                      //   此处接口存在差异性
                      //   经验证 歌单接口与搜索接口回调的数据不一致 缺乏歌曲播放时长 duration
                      //   因此在发现 无时长时需重新获取一遍
                      //   这似乎不是最好的解决办法 或许我的服务端除了问题！
                    */
                    singerDetail(this.song_detail.id).then(res => {
                      this.song_detail.duration = res.data.body.result.songs[0].duration
                    })
                }
                setTimeout(()=>{
                  if(newSong.id == oldSong.id) {
                    return
                  }else{
                    this.$refs.audio.play()
                  }
                },500)
              })
            })
          }
        })
        if(this.currentLyric.stop){
          this.currentLyric.stop()
        }
        getLyrics(id).then(res => {
          let lyric = res.data.body.lrc.lyric
          if(lyric) {
            this.currentLyric = new Lyric(lyric, this.handleLyric)
            if (this.playing) {
              setTimeout(() => {
                this.currentLyric.play()
              },1000)
            }
          }else{
            alert('暂无歌词')
          }
        }).catch(() => {
          this.currentLyric = null
          this.playingLyric = ''
          this.currentLineNum = 0
           alert('歌词请求有误')
        })
      }
    },
    playing(newPlaying) {
      const audio = this.$refs.audio
      newPlaying ? audio.play() : audio.pause()
    },
    playlist () {
      this.getplaylist = this.playlist
    }
  },
  methods: {
    middleTouchStart(e) {
      this.touch.initiated = true
      const touch = e.touches[0]
      this.touch.startX = touch.pageX
      this.touch.startY = touch.pageY
    },
    middleTouchMove(e) {
      if(!this.touch.initiated) {
        return
      }
      const touch = e.touches[0]
      const detaX = touch.pageX - this.touch.startX
      const detaY = touch.pageY - this.touch.startY
      const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      const offsetWidth = Math.min(0,Math.max(-window.innerWidth, left+detaX))
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style['opacity'] = `${this.touch.percent}`
      this.$refs.lyricList.$el.style[transitionDuration] = 0
      this.$refs.middleL.style.opacity = 1 - this.touch.percent
      this.$refs.middleL.style[transitionDuration] = 0
    },
    middleTouchEnd(e) {
      let offsetWidth,opacity
      if(this.currentShow == 'cd' && this.touch.percent > 0.3) {
          this.currentShow = 'lyric'
          offsetWidth = -window.innerWidth
          this.$refs.lyricList.$el.style['opacity'] = 1
          opacity = 0
      }else{
        if(this.touch.percent < 0.9) {
          offsetWidth = 0
          this.currentShow = 'cd'
          opacity = 1
        }else{
          offsetWidth = -window.innerWidth
          opacity = 0
        }
      }
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = 500
      this.$refs.middleL.style.opacity = opacity
    },
    handleLyric({lineNum, txt}) {
      this.currentLineNum = lineNum
      this.playingLyric = txt
      if(this.currentLineNum > 5) {
        let lineEl = this.$refs.lyricLine[this.currentLineNum - 5]
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      }
    },
    changeMode() {
      const mode = (this.mode + 1) % 3
      this.setPlayMode(mode)
      let list = null
      if(mode === playMode.random) {
        list = shuffle(this.sequenceList)
      }else{
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },
    resetCurrentIndex(list){
      /*
        歌曲列表若发生随机排序 则 必须将当前播放歌曲索引取得 设置最新的播放顺序
        这里利用到了H5播放器的一个特点 那就是 如果歌曲发生重复的播放 不会引起进度条的重新计算 播放器会自动按当前播放的进度继续播放
        这样在视觉上就不会产生交替的错觉
      */
      let index = list.findIndex((item) => {
        return item.id === this.currentSong.id
      })
      this.setCurrenIndex(index)
    },
    onProgressBarChange(percent) {
        const currentTime = (this.currentSong.duration/1000) * percent
        this.$refs.audio.currentTime = currentTime
        if(this.currentLyric.seek) {
          this.currentLyric.seek(currentTime * 1000)
        }
    },
    end(){
      if(this.mode == playMode.loop) {
        this.loop()
      }else{
        this.next()
      }
    },
    loop() {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      this.currentLyric.seek()
    },
    format(inteval){
      inteval = inteval | 0
      const minute  = inteval / 60 | 0
      const second = (inteval % 60)
      return `${minute}:${second}`
    },
    updateTime(e) {
      this.currentTime = e.target.currentTime

    },
    ready(){
      this.someReady = true
    },
    error(){
      this.someReady = true
    },
    next(){
      if(!this.someReady) return
      //歌曲列表为1循环播放
      if(this.playlist.length==1) {
        this.loop()
        return
      }
      let index = this.currentIndex+1
      if(index == this.getplaylist.length){
        index = 0
      }
      // 如果正在播放 先停止播放
      if(!this.playing) {
        this.tooglePlaying()
      }
      this.setCurrenIndex(index)
      this.someReady = false
    },
    prev(){
      if(!this.someReady)return
      //歌曲列表为1循环播放
      if(this.playlist.length==1) {
        this.loop()
        return
      }
      let index = this.currentIndex-1
      if(index == -1){
        index = this.getplaylist.length -1
      }
      this.setCurrenIndex(index)
      this.someReady = false
    },
    tooglePlaying() {
      if(!this.someReady)return
      this.setPlayingState(!this.playing)
      this.currentLyric.togglePlay()
    },
    _getPosAndScale() {
      const targetWidth = 40
      const paddingLeft = 40
      const paddingBottom = 30
      const paddingTop = 80
      const width = window.innerWidth * 0.8
      const scale = targetWidth / width
      const x = -(window.innerWidth / 2 - paddingLeft)
      const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
      return {
        x,
        y,
        scale
      }
    },
    enter(el,done) {
      const {x,y,scale} = this._getPosAndScale();
      let animation = {
        0: {
          transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
        },
        60: {
          transform: `translate3d(0,0,0) scale(1.1)`
        },
        100: {
          transform: `translate3d(0,0,0) scale(1)`
        }
      }
      animations.registerAnimation({
        name: 'move',
        animation,
        presets:{
          duration: 400,
          easing: 'linear'
        }
      })
      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter() {
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave(el,done){
      this.$refs.cdWrapper.style.transition = 'all 0.4s'
      const {x, y, scale} = this._getPosAndScale()
      this.$refs.cdWrapper.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave() {
      this.$refs.cdWrapper.style.transition = ''
      this.$refs.cdWrapper.style[transform] = ''
    },
    back () {
      this.setFullScreen(false)
      this.$refs.miniPlayer.style.opacity = 1
    },
    open() {
      this.setFullScreen(true)
      this.$refs.miniPlayer.style.opacity = 0
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN',
      setPlayingState: 'SET_PLAYING_STATE',
      setCurrenIndex: 'SET_CURRENT_INDEX',
      setPlayMode: 'SET_PLAY_MODE',
      setPlayList: 'SET_PLAYLIST'
    }),
  },
}

</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .player
    .normal-player
      position: fixed
      left: 0
      right: 0
      top: 0
      bottom: 0
      z-index: 150
      background: #403d3d
      .background
        position: absolute
        left: 0
        top: 0
        width: 100%
        height: 100%
        z-index: -1
        opacity: 0.6
        filter: blur(20px)
      .top
        position: relative
        margin-bottom: 25px
        .back
          position absolute
          top: 0px
          left: 6px
          z-index: 50
          .icons-xiangxia
            display: block
            padding: 9px
            font-size: $font-size-large-x
            color: $color-theme
        .title
          width: 70%
          margin: 0 auto
          line-height: 40px
          text-align: center
          no-wrap()
          font-size: $font-size-large
          color: $color-text
        .subtitle
          line-height: 20px
          text-align: center
          font-size: $font-size-medium
          color: $color-text
      .middle
        position: fixed
        width: 100%
        top: 80px
        bottom: 170px
        white-space: nowrap
        font-size: 0
        .middle-l
          display: inline-block
          vertical-align: top
          position: relative
          width: 100%
          height: 0
          padding-top: 80%
          .cd-wrapper
            position: absolute
            left: 10%
            top: 0
            width: 80%
            height: 100%
            .cd
              width: 100%
              height: 100%
              box-sizing: border-box
              border: 10px solid rgba(255, 255, 255, 0.1)
              border-radius: 50%
              &.play
                animation: rotate 20s linear infinite
              &.pause
                animation-play-state: paused
              .image
                position: absolute
                left: 0
                top: 0
                width: 100%
                height: 100%
                border-radius: 50%

          .playing-lyric-wrapper
            width: 80%
            margin: 30px auto 0 auto
            overflow: hidden
            text-align: center
            .playing-lyric
              line-height: 20px
              font-size: $font-size-medium
              color: $color-text-l
        .middle-r
          display: inline-block
          vertical-align: top
          width: 100%
          height: 100%
          overflow: hidden
          .lyric-wrapper
            width: 80%
            margin: 0 auto
            overflow: hidden
            text-align: center
            .text
              line-height: 32px
              color: $color-text-l
              font-size: $font-size-medium
              &.current
                color: $color-text
                font-size 16px
      .bottom
        position: fixed
        bottom: 50px
        width: 100%
        .dot-wrapper
          text-align: center
          font-size: 0
          .dot
            display: inline-block
            vertical-align: middle
            margin: 0 4px
            width: 8px
            height: 8px
            border-radius: 50%
            background: $color-text-l
            &.active
              width: 20px
              border-radius: 5px
              background: $color-text-ll
        .progress-wrapper
          display: flex
          align-items: center
          width: 80%
          margin: 0px auto
          padding: 10px 0
          .time
            color: $color-text
            font-size: $font-size-small
            flex: 0 0 30px
            line-height: 30px
            width: 30px
            &.time-l
              text-align: left
            &.time-r
              text-align: right
          .progress-bar-wrapper
            flex: 1
        .operators
          display: flex
          align-items: center
          .icon
            flex: 1
            color: $color-theme
            &.disable
              color: $color-theme-d
            i
              font-size: 22px
          .i-left
            text-align: right
          .i-center
            padding: 0 20px
            text-align: center
            i
              font-size: 40px
          .i-right
            text-align: left
          .icon-favorite
            color: $color-sub-theme
      &.normal-enter-active, &.normal-leave-active
        transition: all .4s
        .top, .bottom
          transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
      &.normal-enter, &.normal-leave-to
        opacity: 0
        .top
          transform: translate3d(0, -100px, 0)
        .bottom
          transform: translate3d(0, 100px, 0)
    .mini-player
      display: flex
      align-items: center
      position: fixed
      left: 0
      bottom: 0
      z-index: 180
      width: 100%
      height: 60px
      background: #444
      opacity 0
      &.mini-enter-active, &.mini-leave-active
        transition: all 0.4s
      &.mini-enter, &.mini-leave-to
        opacity: 0
      .icon
        flex: 0 0 40px
        width: 40px
        padding: 0 10px 0 20px
        img
          border-radius: 50%
          &.play
            animation: rotate 10s linear infinite
          &.pause
            animation-play-state: paused
      .i-img
        position relative
        top -1rem
        img
          border 3px solid #fff
      .text
        display: flex
        flex-direction: column
        justify-content: center
        flex: 1
        line-height: 20px
        overflow: hidden
        .name
          margin-bottom: 2px
          margin-left 2rem
          no-wrap()
          font-size: $font-size-medium
          color: $color-text
        .desc
          no-wrap()
          font-size: $font-size-small
          color: $color-text-d
      .control
        flex: 0 0 30px
        width: auto
        padding: 0 10px
        .icon-play-mini, .icon-pause-mini, .icon-playlist
          color: $color-theme
        .icon-mini
          font-size: 32px
          position: absolute
          left: 0
          top: 0

  @keyframes rotate
    0%
      transform: rotate(0)
    100%
      transform: rotate(360deg)
</style>
